const apiClient = require('./utils/api.js');

App({
    onLaunch: function () {
        console.log('小程序启动');

        // 检查登录状态
        this.checkLoginStatus();
    },

    // 检查登录状态
    async checkLoginStatus() {
        try {
            const token = wx.getStorageSync('auth_token');
            if (token) {
                apiClient.setToken(token);

                // 验证令牌有效性
                const response = await apiClient.getUserProfile();
                if (response && response.success) {
                    this.globalData.isLoggedIn = true;
                    this.globalData.userInfo = response.data.user;
                } else {
                    // 令牌无效，清除本地存储
                    this.clearLoginData();
                }
            }
        } catch (error) {
            console.error('检查登录状态失败:', error);
            this.clearLoginData();
        }
    },

    // 清除登录数据
    clearLoginData() {
        apiClient.clearToken();
        this.globalData.isLoggedIn = false;
        this.globalData.userInfo = {};
    },

    globalData: {
        isLoggedIn: false,
        userInfo: {},
        encryptionKey: 'YourSecretKey123456' // 实际应用中应该从服务器安全获取
    }
});
